package com.yxsk.relay.job.admin.core.trigger.quartz.interceptor;

import com.yxsk.relay.job.admin.core.schedule.quartz.context.TriggerContext;
import com.yxsk.relay.job.admin.core.schedule.quartz.vo.JobConfig;
import com.yxsk.relay.job.admin.core.trigger.interceptor.TaskExecuteInterceptor;
import com.yxsk.relay.job.admin.data.entity.BaseEntity;
import com.yxsk.relay.job.admin.data.entity.JobDetails;
import com.yxsk.relay.job.admin.data.service.JobDetailService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author 11376
 * @CreaTime 2019/6/22 17:21
 * @Description
 */
@Slf4j
@AllArgsConstructor
public class QuartzJobStatusInterceptor implements TaskExecuteInterceptor {

    private JobDetailService detailService;

    @Override
    public boolean intercept(TriggerContext context) {
        JobConfig jobConfig = context.getJobConfig();
        if (jobConfig.getStatus() != JobConfig.JobStatus.NORMAL) {
            if (log.isInfoEnabled()) {
                log.info("Job intercepted, job id: {}. Reason: job status[{}]", jobConfig.getId(), jobConfig.getStatus().getStatus());
            }
            // 任务状态为非正常
            return false;
        }
        JobDetails jobDetails = this.detailService.findById(jobConfig.getId());
        if (jobDetails == null) {
            if (log.isInfoEnabled()) {
                log.info("Job intercepted, job id: {}.Reason: job not found", jobConfig.getId());
            }
            // 任务不存在
            return false;
        }

        if (!BaseEntity.DelFlagEnum.NORMAL.getFlag().equals(jobDetails.getDelFlag())) {
            if (log.isInfoEnabled()) {
                log.info("Job intercepted, job id: {}.Reason: job delete flag is [{}]", jobConfig.getId(), jobDetails.getDelFlag());
            }
            // 任务状态为非正常
            return false;
        }

        return true;
    }

}
